package com.gao.id.support;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class GenRedisId {

    private static final String REDIS_ID_KEY = "redis:id:date:";

    /** 设置一个时间初始值 */
    private long startTimestamp = 1654409438888L;

    /** ID 最大数量 */
    private static final int sequenceBits = 32;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public Long nextId() {
        // 获取当前时间
        long currentStamp = getTimestamp();
        // key 值加上日期加以区分
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        String key = REDIS_ID_KEY + date;
        Long increment = redisTemplate.opsForValue().increment(key);
        return (currentStamp - startTimestamp) << sequenceBits | increment;
    }

    /**获取当前时间戳*/
    public long getTimestamp() {
        return LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
    }

    public static void main(String[] args) {
        // 获取当前时间
        long currentStamp = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        String key = REDIS_ID_KEY + date;
        System.out.println(key);
    }
}
